package cn.jinjimi.app.custom.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import cn.jinjimi.base.util.DateUtils;
import cn.jinjimi.base.util.Lunar;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.framework.helper.annotation.EventTraceSelector;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.bean.QuesCode;
import cn.jinjimi.app.controller.BaseController;
import cn.jinjimi.app.controller.CustomerController;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.controller.event.PhotoInfoEvent;
import cn.jinjimi.app.controller.event.PhotosListEvent;
import cn.jinjimi.app.custom.entity.Custom;
import cn.jinjimi.app.custom.entity.CustomTagData;
import cn.jinjimi.app.custom.event.ClueAddCustomSucEvent;
import cn.jinjimi.app.custom.event.CustomAreaEvent;
import cn.jinjimi.app.custom.event.CustomAvatarUploadEvent;
import cn.jinjimi.app.custom.event.CustomChangeEvent;
import cn.jinjimi.app.custom.event.CustomInfoEvent;
import cn.jinjimi.app.custom.event.CustomPhotosDelEvent;
import cn.jinjimi.app.custom.event.CustomerSearchEvent;
import cn.jinjimi.app.custom.event.TransferCustomEvent;
import cn.jinjimi.app.custom.manager.CustomsManager;
import cn.jinjimi.app.custom.ui.adapter.CustomInfoPhotoEditAdapter;
import cn.jinjimi.app.custom.ui.dialog.EditCustomInfoDialog;
import cn.jinjimi.app.custom.ui.view.CustomAddPhoneView;
import cn.jinjimi.app.entity.PhotoInfo;
import cn.jinjimi.app.store.entity.ClueEntity;
import cn.jinjimi.app.store.entity.custom.ContactInfo;
import cn.jinjimi.app.main.activity.AreaActivity;
import cn.jinjimi.app.main.dialog.CommAlertDialog;
import cn.jinjimi.app.main.dialog.CustomAddPhoneTypeDialog;
import cn.jinjimi.app.main.dialog.DatePickerDialog;
import cn.jinjimi.app.main.dialog.LoadingDialog;
import cn.jinjimi.app.main.extend.ToolBarCommonActivity;
import cn.jinjimi.app.main.widget.LunarDatePicker;
import cn.jinjimi.app.util.MultiplePhotoUtils;
import cn.jinjimi.app.util.NetworkUtils;
import cn.jinjimi.app.util.PhotoUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 新增客户 编辑客户资料
 */
public class CustomEditOrAddActivity extends ToolBarCommonActivity implements
        AdapterView.OnItemClickListener {

    private Custom mCustom = null;
    private ClueEntity mClue = null;

    private ImageView imgAvatar;
    private TextView tvAddAvatar;
    private EditText mEditName;
    private TextView tvIdCard;
    private EditText edIdCode;
    private TextView tvGender;
    private TextView tvProvince;
    private TextView tvCity;

    //客户的生日日期
    private Calendar mCBirthDate = null;
    private int mBirthType = DatePickerDialog.OnDateSetListener.TYPE_GREGORIAN_YEAR;
    private TextView tvBirthday = null;
    private DatePickerDialog mBirthDateDialog = null;

    private EditText edEmail;
    private EditText edAddress;
    private EditText edRemark;
    private TextView tvStatus;
    private TextView tvLevel;

    private LinearLayout mPhoneLayout = null;

    private GridView mGridView;
    private CustomInfoPhotoEditAdapter mAdapter;

    private String mPhotoId;

    private int mCustomGenderType = Custom.CUSTOM_GENDER_NOSET;//性别类型: 0,未设置   1.男    2,女
    private int mCustomIdCodeType = Custom.CUSTOM_IDCODE_NONE; // 证件类型 0 未设置 1 身份证
    private int mCustomType = Custom.CUSTOM_NOT_SET;//客户类型:0为空或者普通客户 , 1为准客户,2为已签单客户
    private int mCustomLevelType = Custom.CUSTOM_NOT_SET;//客户层级:1:A类,2:B类,3:C类,4:D类

    //是否是添加客户时上传图片失败，添加资料成功，上传图片失败
    private boolean mAddCustomUploadFail = false;
    // 是否进来添加客户
    @EventTraceSelector
    public boolean isAddCustom = false;

    // 这次选择的照片是否为头像
    private boolean isPickAvatar = false;
    private String avatarPath;

    private boolean directFinish;

    /* 从浏览页面进入编辑页面 */
    public static void launch(Context startActivity, Custom custom, List<PhotoInfo> photoInfos) {
        Intent intent = new Intent(startActivity, CustomEditOrAddActivity.class);
        intent.putExtra(BundleKey.PARAM_CUSTOM, custom);
        intent.putExtra(BundleKey.PARAM_CUSTOM_PHOTOS, (Serializable) photoInfos);
        startActivity.startActivity(intent);
    }

    /* 从添加手机号码进入编辑页面 */
    public static void launch(Context startActivity, Custom custom, boolean directFinish) {
        Intent intent = new Intent(startActivity, CustomEditOrAddActivity.class);
        intent.putExtra(BundleKey.PARAM_CUSTOM, custom);
        intent.putExtra(BundleKey.PARAM_DIRECT_FINISH, directFinish);
        startActivity.startActivity(intent);
    }

    /* 进入添加用户页面 */
    public static void launch(Context startActivity) {
        Intent intent = new Intent(startActivity, CustomEditOrAddActivity.class);
        startActivity.startActivity(intent);
    }

    /* 从线索详情进入添加新客户 */
    public static void launch(Context startActivity, ClueEntity clue) {
        Intent intent = new Intent(startActivity, CustomEditOrAddActivity.class);
        intent.putExtra(BundleKey.PARAM_CLUE, clue);
        startActivity.startActivity(intent);
    }

    @Override
    protected void beforeInitView() {
        setContentView(R.layout.activity_editcustom);
        setRightText(R.string.done);
        setLeftText(R.string.cancel);
        setSwipeEnabled(false);
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData();
    }

    protected void initView() {
        imgAvatar = (ImageView) findViewById(R.id.img_avatar);
        tvAddAvatar = (TextView) findViewById(R.id.tv_add_avatar);
        mEditName = (EditText) findViewById(R.id.ed_name);
        tvGender = (TextView) findViewById(R.id.tv_gender);
        tvProvince = (TextView) findViewById(R.id.tv_province);
        tvCity = (TextView) findViewById(R.id.tv_city);
        tvBirthday = (TextView) findViewById(R.id.tv_birthday);

        mPhoneLayout = (LinearLayout) findViewById(R.id.ll_addPhone_container);

        tvIdCard = (TextView) findViewById(R.id.tv_id_card);
        edIdCode = (EditText) findViewById(R.id.edt_id_code);

        edEmail = (EditText) findViewById(R.id.edt_email);
        edAddress = (EditText) findViewById(R.id.edt_address);
        edRemark = (EditText) findViewById(R.id.edt_remark);
        tvStatus = (TextView) findViewById(R.id.tv_status);
        tvLevel = (TextView) findViewById(R.id.tv_level);

        mGridView = (GridView) findViewById(R.id.photo_gridview);
        mAdapter = new CustomInfoPhotoEditAdapter(CustomEditOrAddActivity.this);
        mGridView.setAdapter(mAdapter);

        ScrollView view = (ScrollView) findViewById(R.id.scrollview);
        view.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.requestFocusFromTouch();
                return false;
            }
        });
    }

    protected void initListener() {
        findViewById(R.id.ll_avatar).setOnClickListener(this);
        tvBirthday.setOnClickListener(this);
        mGridView.setOnItemClickListener(this);
        findViewById(R.id.add_phone_type_imageView).setOnClickListener(this);
        findViewById(R.id.ll_id_code).setOnClickListener(this);
        findViewById(R.id.layout_addPhone).setOnClickListener(this);
        findViewById(R.id.ll_status).setOnClickListener(this);
        findViewById(R.id.layout_custom_level).setOnClickListener(this);
        findViewById(R.id.tv_gender).setOnClickListener(this);
        findViewById(R.id.layout_custom_area).setOnClickListener(this);

        edIdCode.addTextChangedListener(
                new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        if (mCustomIdCodeType == Custom.CUSTOM_IDCODE_PASSPORT) {
                            String str = StringUtils.passPortFilter(s.toString());
                            if (!edIdCode.getText().toString().equals(str)) {
                                edIdCode.setText(str);
                                edIdCode.setSelection(str.length());
                            }
                        } else if (mCustomIdCodeType == Custom.CUSTOM_IDCODE_ID) {
                            String str = StringUtils.IdCardFilter(s.toString());
                            if (!edIdCode.getText().toString().equals(str)) {
                                edIdCode.setText(str);
                                edIdCode.setSelection(str.length());
                            }
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (mCustomIdCodeType == Custom.CUSTOM_IDCODE_ID && s.length() > 0) {
                            if (s.toString().contains("x")) {
                                edIdCode.setText(s.toString().replace("x", "X"));
                                edIdCode.setSelection(edIdCode.getText().toString().length());
                            } else {
                                String lastIndex = s.toString().substring(s.length() - 1);
                                if (lastIndex.equals("X")) {
                                    if (s.length() > 1) {
                                        String str = s.toString().substring(0, s.length() - 1);
                                        if (str.toString().contains("X")) {
                                            edIdCode.setText(str.toString().replace("X", "") + "X");
                                            edIdCode.setSelection(edIdCode.getText().toString().length());
                                        }
                                    }
                                } else {
                                    if (s.toString().contains("X")) {
                                        edIdCode.setText(s.toString().replace("X", ""));
                                        edIdCode.setSelection(edIdCode.getText().toString().length());
                                    }
                                }
                            }
                        }
                    }
                }

        );
    }

    protected void initData() {
        if (getIntent().hasExtra(BundleKey.PARAM_DIRECT_FINISH))
            directFinish = getIntent().getBooleanExtra(BundleKey.PARAM_DIRECT_FINISH, false);

        if (getIntent().hasExtra(BundleKey.PARAM_CUSTOM))
            mCustom = (Custom) getIntent().getSerializableExtra(BundleKey.PARAM_CUSTOM);

        if (getIntent().hasExtra(BundleKey.PARAM_CLUE)) {
            mClue = (ClueEntity) getIntent().getSerializableExtra(BundleKey.PARAM_CLUE);
            directFinish = true;
        }

        isAddCustom = mCustom == null;

        if (getIntent().hasExtra(BundleKey.PARAM_CUSTOM_PHOTOS)) {
            List<PhotoInfo> photoInfos = (List<PhotoInfo>) getIntent().getSerializableExtra(BundleKey.PARAM_CUSTOM_PHOTOS);
            mAdapter.setItems(photoInfos);
        } else if (!isAddCustom) {
            CustomerController.showPhotosList(mCustom.customerId);
        }

        if (isAddCustom) {
            CustomAddPhoneView defaultPhone = new CustomAddPhoneView(this, mPhoneLayout);
            defaultPhone.setPhoneType(0, CustomAddPhoneTypeDialog.getTypeNameById(0));
            mPhoneLayout.addView(defaultPhone);
            setOnlyTitle(R.string.add_custom);

            if (mClue != null) {
                setClueData();
            }
        } else {
            setData();
            setOnlyTitle(R.string.edit_info);
        }

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_avatar:
                isPickAvatar = true;
                PhotoUtils.pickPhoto(CustomEditOrAddActivity.this, true);
                break;
            case R.id.tv_birthday:
                showDatePickerDialog();
                break;
            case R.id.layout_addPhone:
            case R.id.add_phone_type_imageView:
                CustomAddPhoneView phone = new CustomAddPhoneView(this, mPhoneLayout);
                phone.setPhoneType(0, CustomAddPhoneTypeDialog.getTypeNameById(0));
                mPhoneLayout.addView(phone);
                break;
            case R.id.ll_id_code:
                new EditCustomInfoDialog(this, EditCustomInfoDialog.DIALOGTYPE.SELECT_CUSTOM_IDCODE, new EditCustomInfoDialog.dialogInfoListener() {
                    @Override
                    public void Success(int flag) {
                        setCustomIdCode(flag);//设置证件类型
                    }
                }).show();
                break;
            case R.id.ll_status:
                new EditCustomInfoDialog(this, EditCustomInfoDialog.DIALOGTYPE.SELECT_CUSTOM_STATUS, new EditCustomInfoDialog.dialogInfoListener() {
                    @Override
                    public void Success(int flag) {
                        setCustomStatus(flag);//设置状态
                    }
                }).show();
                break;
            case R.id.layout_custom_level:
                new EditCustomInfoDialog(this, EditCustomInfoDialog.DIALOGTYPE.SELECT_CUSTOM_LEVEL, new EditCustomInfoDialog.dialogInfoListener() {
                    @Override
                    public void Success(int flag) {
                        setCustomLevel(flag);//设置层级
                    }
                }).show();
                break;
            case R.id.tv_gender:
                new EditCustomInfoDialog(this, EditCustomInfoDialog.DIALOGTYPE.SELECT_CUSTOM_GENDER, new EditCustomInfoDialog.dialogInfoListener() {
                    @Override
                    public void Success(int flag) {
                        setCusotmGender(flag);//设置性别
                    }
                }).show();
                break;
            case R.id.layout_custom_area: // 设置地区
                goToAreaActivity();
                break;
        }
    }

    @Override
    @EventTrace({EventID.APP_CUSTOM_EDIT_ADD, EventID.APP_CUSTOM_DETAIL_EDIT_KEEP})
    protected void rightAction() {
        super.rightAction();

        /* 检查网络情况 是Wi-Fi还是其他网络 */
        if (!NetworkUtils.isNetworkConnected(this)) {
            ToastUtils.toastMessage(this, "当前网络不稳定 请稍后再试");
            return;
        }

        if (!NetworkUtils.isWifiAvailable(this) && mAdapter.getUploadItems().size() > 0) {
            getAlertDialog().setTitle("建议您在Wi-Fi网络下再上传图片，可以节省流量哦")
                    .setLeftBtn("取消上传", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            getAlertDialog().dismissDialog();
                        }
                    })
                    .setRightBtn("继续上传", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            getAlertDialog().dismissDialog();
                            saveAction();
                        }
                    }).showDialog(CommAlertDialog.Style.TWO_BUTTON);

        } else {
            saveAction();
        }
    }

    /*设置证件类型*/
    private void setCustomIdCode(int flag) {
        int type = 0;
        switch (flag) {
            case 0:
                type = Custom.CUSTOM_IDCODE_ID;
                tvIdCard.setText(getString(R.string.custom_idcode_id));
                break;
            case 1:
                type = Custom.CUSTOM_IDCODE_PASSPORT;
                tvIdCard.setText(getString(R.string.custom_idcode_passport));
                break;
            case 2:
                type = Custom.CUSTOM_IDCODE_NONE;
                tvIdCard.setText(getString(R.string.empty));
                break;
        }
        if (mCustomIdCodeType != type) {
            mCustomIdCodeType = type;
            edIdCode.setText("");
            setIdcodeType();
        }
    }

    private void setIdcodeType() {
        edIdCode.setEnabled(StringUtils.isNotEmpty(tvIdCard.getText().toString().trim()));
    }

    /* 设置性别 */
    private void setCusotmGender(int flag) {
        switch (flag) {
            case 0://0说明点击的是弹窗item的第一位,以下类推
                mCustomGenderType = Custom.CUSTOM_GENDER_MAN;
                tvGender.setText(getString(R.string.custom_gender_man));
                break;
            case 1:
                mCustomGenderType = Custom.CUSTOM_GENDER_WOMAN;
                tvGender.setText(getString(R.string.custom_gender_woman));
                break;
        }
    }

    /* 设置层级 */
    private void setCustomLevel(int flag) {
        switch (flag) {
            case 0://0说明点击的是弹窗item的第一位,以下类推
                mCustomLevelType = Custom.CUSTOM_LEVEL_A;
                tvLevel.setText(getString(R.string.custom_A));
                break;
            case 1:
                mCustomLevelType = Custom.CUSTOM_LEVEL_B;
                tvLevel.setText(getString(R.string.custom_B));
                break;
            case 2:
                mCustomLevelType = Custom.CUSTOM_LEVEL_C;
                tvLevel.setText(getString(R.string.custom_C));
                break;
            case 3:
                mCustomLevelType = Custom.CUSTOM_LEVEL_D;
                tvLevel.setText(getString(R.string.custom_D));
                break;
            case 4:
                mCustomLevelType = Custom.CUSTOM_NOT_SET;
                tvLevel.setText("");
                break;
        }
    }

    /* 设置状态 */
    private void setCustomStatus(int flag) {
        switch (flag) {
            case 0://0说明点击的是弹窗item的第一位,以下类推
                mCustomType = Custom.TYPE_UNSOLD_CUSTOMER;
                tvStatus.setText(getString(R.string.customer_unsold_text));
                break;
            case 1:
                mCustomType = Custom.TYPE_SOLDED_CUSTOMER;
                tvStatus.setText(getString(R.string.custom_already_written));
                break;
            case 2:
                tvStatus.setText("");
                mCustomType = Custom.CUSTOM_NOT_SET;
                break;
        }
    }

    /* 打开地区选择界面 */
    private void goToAreaActivity() {
        Intent intent = new Intent(CustomEditOrAddActivity.this, AreaActivity.class);
        intent.putExtra(BundleKey.PARAM_HAVE_AREA_RESULT, true);
        if (mCustom != null) {
            intent.putExtra(BundleKey.PARAM_PROVINCE, mCustom.province);
            intent.putExtra(BundleKey.PARAM_CITY, mCustom.city);
        }
        startActivity(intent);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == mAdapter.getItems().size()) {
            isPickAvatar = false;
            PhotoUtils.pickPhoto(CustomEditOrAddActivity.this, Constants.MAX_VALUE_PHOTOS - mAdapter.getItems().size());
        }
    }

    /* 设置线索带来的数据 */
    public void setClueData() {
        mEditName.setText(mClue.realName);
        mEditName.setSelection(mEditName.getText().toString().length());
        mPhoneLayout.removeAllViews();

        CustomAddPhoneView phoneItem = new CustomAddPhoneView(this, mPhoneLayout);
        phoneItem.setPhoneType(0, CustomAddPhoneTypeDialog.getTypeNameById(0));
        phoneItem.setPhone(mClue.phone);
        mPhoneLayout.addView(phoneItem);
    }

    /* 编辑状态下设置客户数据 */
    public void setData() {
        if (StringUtils.isNotEmpty(mCustom.avatar)) {
            imgAvatar.setImageURI(Uri.parse(mCustom.avatar));
            tvAddAvatar.setText(getString(R.string.custom_edit_avatar));
        } else {
            tvAddAvatar.setText(getString(R.string.custom_add_avatar));
        }

        mEditName.setText(mCustom.name);
        mEditName.setSelection(mEditName.getText().toString().length());

        //客户性别
        switch (mCustom.gender) {
            case Custom.CUSTOM_GENDER_MAN:
                tvGender.setText(getString(R.string.custom_gender_man));
                mCustomGenderType = Custom.CUSTOM_GENDER_MAN;
                break;
            case Custom.CUSTOM_GENDER_WOMAN:
                tvGender.setText(getString(R.string.custom_gender_woman));
                mCustomGenderType = Custom.CUSTOM_GENDER_WOMAN;
                break;
            default:
                mCustomGenderType = Custom.CUSTOM_GENDER_NOSET;
                tvGender.setText("");
                break;
        }

        //客户状态
        switch (mCustom.type) {
            case Custom.TYPE_UNSOLD_CUSTOMER:
                tvStatus.setText(getString(R.string.customer_unsold_text));
                mCustomType = Custom.TYPE_UNSOLD_CUSTOMER;
                break;
            case Custom.TYPE_SOLDED_CUSTOMER:
                tvStatus.setText(getString(R.string.custom_already_written));
                mCustomType = Custom.TYPE_SOLDED_CUSTOMER;
                break;
            default:
                tvStatus.setText("");//未设置
                mCustomType = Custom.CUSTOM_NOT_SET;
                break;
        }

        //客户层级
        switch (mCustom.category) {
            case Custom.CUSTOM_LEVEL_A:
                tvLevel.setText(getString(R.string.custom_A));
                mCustomLevelType = Custom.CUSTOM_LEVEL_A;
                break;
            case Custom.CUSTOM_LEVEL_B:
                tvLevel.setText(getString(R.string.custom_B));
                mCustomLevelType = Custom.CUSTOM_LEVEL_B;
                break;
            case Custom.CUSTOM_LEVEL_C:
                tvLevel.setText(getString(R.string.custom_C));
                mCustomLevelType = Custom.CUSTOM_LEVEL_C;
                break;
            case Custom.CUSTOM_LEVEL_D:
                tvLevel.setText(getString(R.string.custom_D));
                mCustomLevelType = Custom.CUSTOM_LEVEL_D;
                break;
            default:
                tvLevel.setText("");
                mCustomLevelType = Custom.CUSTOM_NOT_SET;
                break;
        }

        // 设置证件类型
        mCustomIdCodeType = mCustom.idCard;
        tvIdCard.setText(mCustomIdCodeType == 0 ? "" : Custom.getIdCardStr(mCustomIdCodeType, CustomEditOrAddActivity.this));

        setIdcodeType();

        edIdCode.setText(mCustom.idCode);
        edEmail.setText(mCustom.email);
        if (StringUtils.isNotEmpty(mCustom.province)) {
            tvProvince.setText(mCustom.province);
            tvProvince.setHint("");
        }

        tvCity.setText(mCustom.city);
        edAddress.setText(mCustom.address);
        edRemark.setText(mCustom.remark);

        mPhoneLayout.removeAllViews();
        if (mCustom.getContactInfos() != null && mCustom.getContactInfos().size() > 0) {
            for (ContactInfo phone : mCustom.getContactInfos()) {
                CustomAddPhoneView phoneItem = new CustomAddPhoneView(this, mPhoneLayout);
                phoneItem.setPhoneType(phone.getType(), CustomAddPhoneTypeDialog.getTypeNameById(phone.getType()));
                phoneItem.setPhone(phone.getValue());
                mPhoneLayout.addView(phoneItem);
            }
        } else {
            CustomAddPhoneView defaultPhone = new CustomAddPhoneView(this, mPhoneLayout);
            defaultPhone.setPhoneType(0, CustomAddPhoneTypeDialog.getTypeNameById(0));
            mPhoneLayout.addView(defaultPhone);
        }

        mBirthType = mCustom.birthdayType;
        if (!TextUtils.isEmpty(mCustom.birthday)) {
            mCBirthDate = Calendar.getInstance();
            mCBirthDate.setTimeInMillis(Long.parseLong(mCustom.birthday));

            if (mBirthType == DatePickerDialog.OnDateSetListener.TYPE_GREGORIAN_NO_YEAR
                    || mBirthType == DatePickerDialog.OnDateSetListener.TYPE_GREGORIAN_YEAR) {
                String bir;
                if (mBirthType == DatePickerDialog.OnDateSetListener.TYPE_GREGORIAN_YEAR)
                    bir = String.format(getString(R.string.custom_birthday_has_year_born), mCBirthDate.get(Calendar.YEAR), mCBirthDate.get(Calendar.MONTH) + 1, mCBirthDate.get(Calendar.DAY_OF_MONTH));
                else
                    bir = String.format(getString(R.string.custom_birthday_no_year_born), mCBirthDate.get(Calendar.MONTH) + 1, mCBirthDate.get(Calendar.DAY_OF_MONTH));
                tvBirthday.setText(bir);
            } else {
                Lunar lunar = new Lunar(mCBirthDate);

                if (mBirthType == DatePickerDialog.OnDateSetListener.TYPE_LUNAR_NO_YEAR)
                    tvBirthday.setText(String.format(getString(R.string.custom_lunar_born), lunar.toString()));
                else
                    tvBirthday.setText(String.format(getString(R.string.custom_lunar_born), lunar.getLunarString()));
            }
        }
    }

    /* 保存操作 */
    private void saveAction() {

        if (isAddCustom) {
            doAddCustom();
        } else {
            updateCustom();
        }
    }

    /* 新增用户前进行前置处理 */
    private void doAddCustom() {
        if (!varifyUpdate())
            return;

        LoadingDialog.showForce(this, getString(R.string.saving_wait));
        boolean haveSame = false;

        if (mClue != null) {// 线索不为空的情况
            for (int i = 0; i < mPhoneLayout.getChildCount(); i++) {
                CustomAddPhoneView view = (CustomAddPhoneView) mPhoneLayout.getChildAt(i);
                if (StringUtils.isNotEmpty(view.getPhone()) && view.getPhone().equals(mClue.phone)) {
                    haveSame = true;
                    break;
                }
            }
        }

        if (haveSame)
            CustomsManager.getInstance().searchCustomertWithPhone(mClue.phone);
        else
            addCustom();
    }

    /* 新增客户,必须填写用户姓名 */
    private void addCustom() {
        List<ContactInfo> phones = new ArrayList<>();
        for (int i = 0; i < mPhoneLayout.getChildCount(); i++) {
            CustomAddPhoneView view = (CustomAddPhoneView) mPhoneLayout.getChildAt(i);
            if (StringUtils.isNotEmpty(view.getPhone()))
                phones.add(new ContactInfo(view.getPhoneType(), view.getPhone()));
        }
        Custom custom = new Custom(mEditName.getText().toString().trim(),
                getBirthday(),
                mBirthType,
                phones,
                BaseController.SOURCE_APP,
                AccountManager.getInstance().getAccount().ssoid,
                mCustomType,      //客户类别
                mCustomGenderType,//客户性别
                mCustomLevelType, //客户层级
                edEmail.getText().toString().trim(),
                mCustomIdCodeType,
                edIdCode.getText().toString().trim(),
                tvProvince.getText().toString().trim(),
                tvCity.getText().toString().trim(),
                edAddress.getText().toString().trim(),
                edRemark.getText().toString().trim());

        CustomsManager.getInstance().addCustom(custom, avatarPath, mClue == null ? null : mClue.clueId);

        setRightBtnEnable(false);
    }

    /* 生日类型转换 */
    private String getBirthday() {
        if (mCBirthDate == null)
            return "";
        else
            return DateUtils.formatyymmdd(mCBirthDate.getTimeInMillis());
    }

    /* 修改客户资料 */
    private void updateCustom() {
        if (!hasEdit()) {
            finish();
            return;
        }

        if (!varifyUpdate())
            return;

        LoadingDialog.showForce(this, getString(R.string.custom_update_ing));
        List<ContactInfo> mPhones = getCustomPhones();
        Custom custom = new Custom(mEditName.getText().toString().trim(),
                mCustom.customerId,
                getBirthday(),
                mBirthType,
                mPhones,
                AccountManager.getInstance().getAccount().ssoid,
                mCustomType,       //客户类别
                mCustomGenderType, //客户性别
                mCustomLevelType,  //客户层级
                new ArrayList<CustomTagData>(),   //需要添加的全新的标签
                mCustom.label,          //需要添加的可选标签的ID群,如1,2,3,4
                edEmail.getText().toString().trim(),
                mCustomIdCodeType,
                edIdCode.getText().toString().trim(),
                tvProvince.getText().toString().trim(),
                tvCity.getText().toString().trim(),
                edAddress.getText().toString().trim(),
                edRemark.getText().toString().trim());

        CustomsManager.getInstance().updateCustom(custom, avatarPath);
        setRightBtnEnable(false);
    }

    /* 验证是否可以提交 */
    private boolean varifyUpdate() {
        String needname = mEditName.getText().toString().trim();
        if (TextUtils.isEmpty(needname)) {
            ToastUtils.toastMessage(CustomEditOrAddActivity.this, getString(R.string.custom_add_need_input_name));
            return false;
        }

        String idCard = edIdCode.getText().toString().trim();
        if (StringUtils.isNotEmpty(idCard)) {
            if (StringUtils.isEmpty(tvIdCard.getText().toString())) {
                ToastUtils.toastMessage(CustomEditOrAddActivity.this, R.string.custom_id_code_empty);
                return false;
            }

            if (mCustomIdCodeType == Custom.CUSTOM_IDCODE_ID && !StringUtils.isIDcard(idCard)) {
                ToastUtils.toastMessage(CustomEditOrAddActivity.this, R.string.custom_id_card_error);
                return false;
            }
        }

        String email = edEmail.getText().toString().trim();
        if (StringUtils.isNotEmpty(email) && !StringUtils.isEmail(email)) {
            ToastUtils.toastMessage(CustomEditOrAddActivity.this, R.string.custom_email_error);
            return false;
        }

        List<ContactInfo> customPhones = getCustomPhones();
        if (customPhones.size() > 1) {
            List<String> phones = new ArrayList<>();
            Set<String> phoneSet = new HashSet<>();
            for (ContactInfo contactInfo : customPhones) {
                phones.add(contactInfo.getValue());
                phoneSet.add(contactInfo.getValue());
            }
            if (phones.size() > phoneSet.size()) {
                ToastUtils.toastMessage(CustomEditOrAddActivity.this, R.string.custom_same_phone);
                return false;
            }
        }

        return true;
    }

    /* 发送通知 */
    private void sendEvent2Others(Custom custom) {
        EventBus.getDefault().post(new CustomChangeEvent(custom));
    }

    /* 监听获取客户信息 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onfinal(final CustomInfoEvent event) {
        setRightBtnEnable(true);

        switch (event.state) {
            case DataEvent.SUCC:
                final Custom custom = event.data;
                if (custom == null)
                    return;

                mCustom = custom;
                sendEvent2Others(custom);

                if (isAddCustom && mClue != null) {// 根据线索新增客户成功
                    onAddCustomerSucc();
                }

                handPhotos();

                break;
            case DataEvent.FAIL:
                LoadingDialog.dispose();
                fail((String) event.msg);
                break;
        }
    }

    @EventTrace(EventID.APP_CUSTOMER_EDITDETAIL_CREATESUCCESS)
    private void onAddCustomerSucc() {
        EventBus.getDefault().post(new ClueAddCustomSucEvent(mClue, mCustom));
    }

    /* 监听上传头像结果 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCustomAvatarUploadEvent(CustomAvatarUploadEvent event) {
        switch (event.state) {
            case DataEvent.SUCC:
                avatarPath = "";
                break;
            case DataEvent.FAIL:
                ToastUtils.toastMessage(CustomEditOrAddActivity.this, "客户头像上传失败，请重试");
                break;
        }
    }

    /* 处理图片逻辑 */
    private void handPhotos() {
        if (isAddCustom) {
            if (mAdapter.getItems().size() > 0) {
                uploadPhotos();
            } else {
                gotoCustomArchives();
            }
        } else {
            if (mPhotoId == null && mAdapter.getUploadItems().size() == 0) {//没有需要上传或者删除的图片
                ToastUtils.toastMessage(CustomEditOrAddActivity.this, getString(R.string.save_success));
                LoadingDialog.dispose();
                gotoCustomInfo();
            }
            if (mPhotoId == null) { //先删除图片在上传图片.
                if (mAdapter.getUploadItems().size() > 0) {
                    uploadPhotos(); // 上传图片
                }
            } else {
                CustomerController.deleteCustomPhotos(mCustom.customerId, mPhotoId); // 删除客户的照片
            }
        }
    }

    /* 上传图片 */
    public void uploadPhotos() {

    }

    /* 监听获取相册返回的信息 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPhotosListEvent(PhotosListEvent event) {
        switch (event.state) {
            case PhotosListEvent.SUCC:
                List<PhotoInfo> photoInfo = event.data.getAttachements();
                mAdapter.setItems(photoInfo);
                break;
            case PhotosListEvent.FAIL:
                ToastUtils.toastMessage(CustomEditOrAddActivity.this, "获取照片失败,请稍后重试");
                break;
        }
    }

    /* 监听删除照片 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCustomPhotosDelEvent(CustomPhotosDelEvent event) {
        switch (event.state) {
            case DataEvent.SUCC:
                if (mAdapter.getUploadItems().size() > 0) {
                    // 上传图片
                    uploadPhotos();
                } else {
                    LoadingDialog.dispose();
                    ToastUtils.toastMessage(CustomEditOrAddActivity.this, getString(R.string.save_success));
                    gotoCustomInfo();
                }
                break;
            case DataEvent.FAIL:
                LoadingDialog.dispose();
                ToastUtils.toastMessage(CustomEditOrAddActivity.this, getString(R.string.custom_update_fail));
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPhotoInfoEvent(PhotoInfoEvent event) {
        if (event.state == PhotoInfoEvent.DELETE) {
            int positon = event.position;
            if (StringUtils.isEmpty(mPhotoId)) {
                mPhotoId = event.id;
            } else {
                mPhotoId = mPhotoId + "," + event.id;
            }
            mAdapter.removeItem(positon);
        }
    }

    /* 监听传出来的地区信息 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCustomAreaEvent(CustomAreaEvent event) {
        if (event.province != null) {
            tvProvince.setText(event.province.provinceName);
            tvProvince.setHint("");
        }

        if (event.city != null)
            tvCity.setText(event.city.cityName);
    }

    /* 监听查询相同手机号码的问题 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCustomerSearchEvent(CustomerSearchEvent event) {
        if (event.mResult != null && mClue != null && event.mResult.getPhone().equals(mClue.phone)) {
            if (event.mResult.getList().isEmpty()) {
                addCustom();
            } else {
                LoadingDialog.dispose();
                showTransferDialog(event.mResult.getList());
            }
        }
    }

    /* 监听关联单个用户的回调 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTransferCustomEvent(TransferCustomEvent event) {

    }

    /* 客户被删或为空的处理 */
    public void customNull() {
        getAlertDialog().setTitle(getString(R.string.custom_null))
                .setMessage("")
                .setRightBtn(getString(R.string.custom_i_know), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getAlertDialog().dismissDialog();
                        CustomsManager.getInstance().deleteCustom(selectCustom, true);
                        EventBus.getDefault().post(new CustomChangeEvent(selectCustom, CustomChangeEvent.EVENT_DELETE));
                    }
                });
        getAlertDialog().setCancelable(false);
        getAlertDialog().showDialog(CommAlertDialog.Style.ONE_BUTTON);
    }

    private Custom selectCustom;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onClueAddCustomSucEvent(ClueAddCustomSucEvent event) {
        if (mClue.clueId.equals(event.clue.clueId))
            finish();
    }

    /* 弹出显示关联提醒的dialog */
    private void showTransferDialog(final List<Custom> samePhoneCustoms) {
        String message;
        String rightButtonText;
        if (samePhoneCustoms.size() == 1) {
            message = String.format(getString(R.string.clue_save_fail_msg_one_custm), samePhoneCustoms.get(0).name);
            rightButtonText = String.format(getString(R.string.clue_transfer_for), samePhoneCustoms.get(0).name);
        } else {
            message = String.format(getString(R.string.clue_save_fail_msg_more_custm));
            rightButtonText = getString(R.string.clue_transfer);
        }
        getAlertDialog().setTitle(getString(R.string.clue_save_fail))
                .setMessage(message)
                .setRightBtn(rightButtonText, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (samePhoneCustoms.size() == 1) {
                            CustomerController.transferCustom(mClue.clueId, samePhoneCustoms.get(0).customerId);
                            selectCustom = samePhoneCustoms.get(0);
                            LoadingDialog.showForce(CustomEditOrAddActivity.this, getString(R.string.transfer_customing));
                        } else {
                            SelectCustomActivity.launch(CustomEditOrAddActivity.this, mClue, QuesCode.QuestSelectTranferCode);
                        }
                    }
                });
        getAlertDialog().setCanceledOnTouchOutside(false);
        getAlertDialog().showDialog(CommAlertDialog.Style.TWO_BUTTON);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (isPickAvatar) {
            avatarPath = PhotoUtils.handlePhotoResult(CustomEditOrAddActivity.this, data, requestCode, resultCode);
            if (StringUtils.isNotEmpty(avatarPath)) {
                imgAvatar.setImageURI(Uri.parse("file://" + avatarPath));
            }
            return;
        }
        switch (requestCode) {
            case QuesCode.RequestCodeMultipleAlbum:
                mAdapter.addItems(MultiplePhotoUtils.getInstance().getPhotoList());
                MultiplePhotoUtils.getInstance().clearPhotoList();
                break;
            case QuesCode.RequestCodeCamera:
                String path = PhotoUtils.handlePhotoResult(CustomEditOrAddActivity.this, data, requestCode, resultCode);
                if (null != path) {
                    PhotoInfo photoInfo = new PhotoInfo(path);
                    mAdapter.addItem(photoInfo);
                    MultiplePhotoUtils.getInstance().clearPhotoList();
                }
                break;
        }
    }

    /* 日期选择弹窗 */
    private void showDatePickerDialog() {
        Calendar today = Calendar.getInstance();
        today.set(1990, 0, 1);
        if (mCBirthDate != null)
            today = mCBirthDate;

        if (mBirthDateDialog == null) {
            mBirthDateDialog = new DatePickerDialog(CustomEditOrAddActivity.this,
                    mDatelistener, mBirthType,
                    today.get(Calendar.YEAR),
                    today.get(Calendar.MONTH),
                    today.get(Calendar.DAY_OF_MONTH));
        }
        mBirthDateDialog.updateDate(today.get(Calendar.YEAR),
                today.get(Calendar.MONTH),
                today.get(Calendar.DAY_OF_MONTH),
                mBirthType);
        mBirthDateDialog.show();
    }

    private DatePickerDialog.OnDateSetListener mDatelistener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(LunarDatePicker view, Calendar date, String dateStr, int type) {
            mBirthType = type;
            mCBirthDate = date;
            if (mBirthType == DatePickerDialog.OnDateSetListener.TYPE_LUNAR_NO_YEAR ||
                    mBirthType == DatePickerDialog.OnDateSetListener.TYPE_LUNAR_YEAR) {
                tvBirthday.setText(String.format(getString(R.string.custom_lunar_born), dateStr));
            } else {
                tvBirthday.setText(String.format(getString(R.string.custom_birthday_born), dateStr));
            }
        }
    };

    /* 前往跟进客户的页面 */
    public void gotoCustomArchives() {
        hideLoadingIndicator();
        ToastUtils.toastMessage(CustomEditOrAddActivity.this, getString(R.string.save_success));
        if (!directFinish)
            CustomArchivesActivity.launch(this, mCustom);
        finish();
    }

    /* 打开客户详情界面 */
    private void gotoCustomInfo() {
        if (directFinish)
            finish();
        else
            CustomInfoActivity.launch(CustomEditOrAddActivity.this, mCustom);
    }

    //查看是否有修改
    private boolean hasEdit() {
        List<ContactInfo> phones = getCustomPhones();
        if (isAddCustom) {
            boolean isFromClue = mClue != null;
            if ((!isFromClue && StringUtils.isNotEmpty(mEditName.getText().toString().trim())) ||
                    (isFromClue && !mEditName.getText().toString().trim().equals(mClue.realName)))
                return true; // 判断姓名
            if (isFromClue) {
                String cluePhone = mClue.phone;
                boolean isCluePhoneEmpty = StringUtils.isEmpty(cluePhone);
                if (isCluePhoneEmpty && !phones.isEmpty()) return true;
                if (!isCluePhoneEmpty) {
                    if ((phones.size() >= 2 || phones.size() == 0))
                        return true;
                    String phone = phones.get(0).getValue();
                    if (!phone.equals(mClue.phone)) return true;
                }
            }

            if (StringUtils.isNotEmpty(avatarPath)) return true;                            // 判断头像
            if (mCustomGenderType != Custom.CUSTOM_GENDER_NOSET) return true;               // 判断性别
            if (mCustomType != Custom.CUSTOM_NOT_SET) return true;                          // 判断状态
            if (mCustomLevelType != Custom.CUSTOM_NOT_SET) return true;                     // 判断层级
            if (!isFromClue && phones.size() > 0) return true;                             // 判断电话
            if (mCBirthDate != null) return true;                                           // 判断生日
            if (mCustomIdCodeType != Custom.CUSTOM_IDCODE_NONE)
                return true;                // 判断证件类型
            if (StringUtils.isNotEmpty(edIdCode.getText().toString().trim()))
                return true;  // 判断证件号码
            if (StringUtils.isNotEmpty(tvIdCard.getText().toString().trim()))
                return true;  // 判断证件类型
            if (StringUtils.isNotEmpty(edEmail.getText().toString().trim())) return true;   // 判断邮件
            if (StringUtils.isNotEmpty(tvProvince.getText().toString().trim())) return true;// 判断地区
            if (StringUtils.isNotEmpty(edAddress.getText().toString().trim())) return true; // 判断地址
            if (StringUtils.isNotEmpty(edRemark.getText().toString().trim())) return true;  // 判断备注
        } else {
            if (!mCustom.name.equals(mEditName.getText().toString().trim()))
                return true;                                                                //判断姓名

            if (StringUtils.isNotEmpty(avatarPath))                                         //判断头像
                return true;

            if (mCustom.type != mCustomType) return true;                              //判断状态
            if (mCustomLevelType != mCustom.category) return true;                     //判断层级
            if (mCBirthDate != null
                    && !String.valueOf(mCBirthDate.getTimeInMillis()).equals(mCustom.birthday)) { //判断生日
                return true;
            }
            if (judgePhones(phones)) return true;                                           //判断电话
            if (mCustom.gender != mCustomGenderType) return true;                      //判断性别
            if (mCustom.idCard != mCustomIdCodeType) return true;                     //判断证件类型
            if (mCustom.idCode != null && !mCustom.idCode.equals(edIdCode.getText().toString()))
                return true;
            if (mCustom.idCode == null && StringUtils.isNotEmpty(edIdCode.getText().toString()))
                return true;                                                                // 判断证件号码

            if (mCustom.email != null && !mCustom.email.equals(edEmail.getText().toString().trim()))
                return true; // 判断邮箱
            if (mCustom.email == null && StringUtils.isNotEmpty(edEmail.getText().toString().trim()))
                return true;

            if (mCustom.province != null && !mCustom.province.equals(tvProvince.getText().toString().trim()))
                return true; // 判断省份
            if (mCustom.province == null && StringUtils.isNotEmpty(tvProvince.getText().toString().trim()))
                return true;

            if (mCustom.city != null && !mCustom.city.equals(tvCity.getText().toString().trim()))
                return true; // 判断城市
            if (mCustom.city == null && StringUtils.isNotEmpty(tvCity.getText().toString().trim()))
                return true;

            if (mCustom.address != null && !mCustom.address.equals(edAddress.getText().toString().trim()))
                return true; // 判断地址
            if (mCustom.address == null && StringUtils.isNotEmpty(edAddress.getText().toString().trim()))
                return true;

            if (mCustom.remark != null && !mCustom.remark.equals(edRemark.getText().toString().trim()))
                return true; // 判断备注
            if (mCustom.remark == null && StringUtils.isNotEmpty(edRemark.getText().toString().trim()))
                return true;

        }
        //判断是否有需要删除的图片
        if (mPhotoId != null) return true;
        //判断是否有需要上传的图片
        return mAdapter.getUploadItems().size() > 0;
    }

    /* 判断电话 */
    private boolean judgePhones(List<ContactInfo> phones) {
        if ((mCustom.getContactInfos() == null && phones.size() > 0) || (mCustom.getContactInfos() != null && mCustom.getContactInfos().size() != phones.size())) {
            return true;
        } else {
            for (int i = 0; i < phones.size(); i++) {
                ContactInfo news = phones.get(i);
                boolean hasEqualsItem = false;
                for (ContactInfo old : mCustom.getContactInfos()) {
                    if (news.getValue().equals(old.getValue()) && news.getType().equals(old.getType())) {
                        hasEqualsItem = true;
                        break;
                    }
                }
                if (!hasEqualsItem)
                    return true;
            }
        }
        return false;
    }

    @NonNull
    private List<ContactInfo> getCustomPhones() {
        int count = mPhoneLayout.getChildCount();
        List<ContactInfo> phones = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            CustomAddPhoneView item = (CustomAddPhoneView) mPhoneLayout.getChildAt(i);
            if (StringUtils.isNotEmpty(item.getPhone())) {
                phones.add(new ContactInfo(item.getPhoneType(), item.getPhone()));
            }
        }
        return phones;
    }

    @Override
    public void onBackPressed() {
        if (hasEdit()) {
            cancelEditAlert();
        } else super.onBackPressed();
    }

    /* 提示弹窗 */
    public void cancelEditAlert() {
        getAlertDialog().setTitle(getString(R.string.giveup_edit))
                .setMessage(getString(R.string.giveup_edit_msg))
                .setRightBtn(getString(R.string.ok), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getAlertDialog().dismissDialog();
                        finish();
                    }
                });
        getAlertDialog().setCanceledOnTouchOutside(false);
        getAlertDialog().showDialog(CommAlertDialog.Style.TWO_BUTTON);
    }

    public void fail(String msg) {
        if (isAddCustom) {
            ToastUtils.toastMessage(this, msg != null ? msg : getString(R.string.custom_add_fail));
        } else {
            ToastUtils.toastMessage(this, msg != null ? msg : getString(R.string.custom_update_fail));
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isOnpause = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        isOnpause = false;
    }

    boolean isOnpause;
}